from django.shortcuts import render, HttpResponse, redirect
import requests
from app01 import models


# Create your views here.
def index(request):
    return HttpResponse("首页")


# 根据settings.py的app的注册顺序，逐一去他们各自的templates目录下去找对应的html文件
def user_list(request):
    return render(request, "user_list.html")


def user_add(request):
    return HttpResponse("添加用户")


def test_img(request):
    return render(request, "test_img.html")


def tpl(request):
    name = "用户"
    roles = ["管理员", "操作员", "普通用户"]
    user_info = {"name": "张三", "age": 19, "salary": 1000}
    data_list = [
        {"name": "张三", "age": 19, "salary": 1000},
        {"name": "李三", "age": 18, "salary": 1000},
        {"name": "王三", "age": 17, "salary": 1000}
    ]
    return render(request, "tpl.html", {"n1": name, "n2": roles, "n3": user_info, "n4": data_list})


def baidu(request):
    # 引入第三方模块requests(pip requests)
    res = requests.get(
        "https://music.91q.com/v1/tracklist/list?sign=7badb8ec51da44eff18e6b91e9b61782&pageSize=50&appid=16073360&timestamp=1648371843")
    data_list = res.json()
    print(data_list)
    return HttpResponse("返回数据")


def something(request):
    # request是一个对象，封装了用户发送过来的请求的所有数据
    # 1、获取请求方式
    print(request.method)
    # 2、获取get请求的参数 ?name=123&age=10
    print(request.GET)
    # 3、获取post请求的参数
    print(request.POST)
    # 4、返回字符串，将字符串返回给请求者
    # return HttpResponse("返回内容")
    # 5、返回html
    # return render(request,something.html)
    # 6、让浏览器重定向到其他页面
    return redirect("https://www.baidu.com/")


def pymysql(request):
    # 引pymsql
    import pymysql
    # 连接数据库
    conn = pymysql.connect(host="localhost", port=3306, user="root", password="root")
    cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
    # 发送sql
    cursor.execute("select * from shop.shop_order")
    data = cursor.fetchall()
    print(data)
    # 关闭
    cursor.close()
    conn.close()

    return HttpResponse("返回内容")


def orm(request):
    # # 添加数据
    # models.UserInfo.objects.create(name="张三",password="123",age=19)
    # models.UserInfo.objects.create(name="李三",password="456",age=19)
    # models.UserInfo.objects.create(name="王三",password="789",age=19)
    #
    # models.Department.objects.create(title="销售部")
    # models.Department.objects.create(title="研发部")
    # models.Department.objects.create(title="运营部")
    # # 删除数据
    # models.UserInfo.objects.filter(id=3).delete()
    # models.Department.objects.all().delete()

    # 获取数据
    # data_list [对象,对象,对象] QuerySet类型
    # data_list = models.UserInfo.objects.all()
    # for obj in data_list:
    #     print(obj.id, obj.name, obj.password, obj.age)
    # row_obj = models.UserInfo.objects.filter(id=1).first()
    # print(row_obj.name,row_obj.age,row_obj.password)

    # 更新数据
    models.UserInfo.objects.all().update(age=100)
    models.UserInfo.objects.filter(id=4).update(age=30)



    return HttpResponse("操作成功")
